package think.in.java.concurrency.practise.exec6;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by IntelliJ IDEA.
 * User: Richard
 * Date: 5/19/11
 * Time: 9:21 PM
 * simple sample for reentrantlock
 */
public class LockExec {
    private ReentrantLock lock = new ReentrantLock();
    public void untimed(){
        boolean captured = lock.tryLock();
        try{
            System.out.println("tryLock" + captured);
        }
        finally {
            if(captured){
                lock.unlock();
            }
        }
    }

    public void timed(){
        boolean captured = false;
        try{
            captured = lock.tryLock(2,TimeUnit.SECONDS);
            System.out.println("tryLock2" + captured);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            if(captured)
               lock.unlock();
        }
    }
    public static void main(String[] args){
        final LockExec lockExec =new LockExec();
        //first time , dont have the lock
        lockExec.timed();
        lockExec.untimed();
        new Thread(){
            {setDaemon(true);}
            public void run(){
                //lock in another thread
                lockExec.lock.lock();
                System.out.println("acquired!");
            }
        }.start();
        Thread.yield();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        //try the locked lock
        lockExec.untimed();
        lockExec.timed();


    }
}
